package middlewares

import (
	"bytes"
	"fmt"
	"os"
	"runtime"

	"gitee.com/fkil555/gin-extend/conf"
	cronContext "gitee.com/fkil555/gin-extend/cron/context"
)

// 调用栈
func stack(skip int) string {
	buf := new(bytes.Buffer)

	for i := skip; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
	}
	return buf.String()
}

// 崩溃日志中间件
func Recovery() cronContext.HandleFunc {
	return func(context *cronContext.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 调试输出到命令行
				if conf.GEConf.Debug != 0 {
					fmt.Fprintln(os.Stderr, err, stack(3))
				}
			}
		}()

		// 调用下一个中间件
		context.Next()
	}
}
